import { Button, Card, Col, Pagination, Popconfirm, Row, Space, Table, Tag } from 'antd'
import React, { useState, useEffect } from 'react'
import PageBreadcrumb from '../../components/PageBreadcrumb'
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons'
import { getCategoriesList, deleteCategories } from "../../api/categories.js";
import Message from '../../components/Message'
import AddOrEditCategories from './AddOrEditCategories'

const showTotal = (total) => `共 ${total} 条`;
const CategoriesList = () => {
  const text = '此操作将永久删除该分类, 是否继续?';
  const isDeleted = (cat_deleted) => {
    if (!cat_deleted) {
      return <CheckCircleOutlined style={{ color: 'green' }} />
    } else {
      return <CloseCircleOutlined style={{ color: 'red' }} />
    }
  }
  const levelTag = (level) => {
    let color = ''
    let label = ''
    if (level === 0) {
      color = 'blue'
      label = '一级'
    } else if (level === 1) {
      color = 'green'
      label = '二级'
    } else {
      color = 'orange'
      label = '三级'
    }
    return <Tag color={color}>{label}</Tag>
  }
  const columns = [
    {
      title: '分类名称',
      dataIndex: 'cat_name',
      key: 'cat_name'
    },
    {
      title: '是否有效',
      key: 'cat_deleted',
      dataIndex: 'cat_deleted',
      render: (cat_deleted) => (
        <>
          {isDeleted(cat_deleted)}
        </>

      ),
    },
    {
      title: '排序',
      key: 'cat_level',
      dataIndex: 'cat_level',
      render: (cat_level) => (
        <>
          {levelTag(cat_level)}
        </>

      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button type='link' onClick={() => handleEdit(record)}>编辑</Button>
          <Popconfirm
            placement="top"
            title={text}
            onConfirm={() => handleDelete(record.cat_id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type='link'>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const [data, setData] = useState([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [queryInfo, setQueryInfo] = useState({
    type: 3,
    pagenum: 1, // 当前的页数
    pagesize: 10, // 当前每页显示多少条数据
  });
  const [isAddOrEdit, setIsAddOrEdit] = useState(false) // 控制对话框的显示和隐藏
  const [catInfo, setCatInfo] = useState({})
  const [parentCate, setParentCate] = useState({})

  useEffect(() => {
    getParentCateList()
  }, [])

  useEffect(() => {
    getListData()
  }, [queryInfo])

  // 获取弹框父级分类数据
  const getParentCateList = async () => {
    const data = await getCategoriesList({type: 2});
    setParentCate(data)
  };

  // 查询列表
  const getListData = async () => {
    setLoading(true)
    const data = await getCategoriesList(queryInfo).finally(() => {
      setLoading(false)
    });

    setData(data.result)
    setTotal(data.total)

  };

  // 监听页码值的改变
  const handlePagination = (page, pageSize) => {
    setQueryInfo({
      type: 3,
      pagenum: page,
      pagesize: pageSize
    })
  }

  // 编辑
  const handleEdit = (row) => {
    setIsAddOrEdit(true)
    setCatInfo(row)
  };

  // 删除
  const handleDelete = async (id) => {
    await deleteCategories(id);
    Message("success", "删除成功");
    getListData();
    getParentCateList()
  };

  // 关闭添加/编辑对话框
  const hideAddOrEdit = (type) => {
    setCatInfo({})
    setIsAddOrEdit(false)
    if (type === 'success') {
      getListData()
      getParentCateList()
    }
  }

  return (
    <>
      <PageBreadcrumb>
        <span>商品管理</span>
        <span>商品分类</span>
      </PageBreadcrumb>

      <Card>
        <Row>
          <Col>
            <Button type="primary" onClick={() => setIsAddOrEdit(true)}>添加分类</Button>
          </Col>
        </Row>

        <Table
          rowKey="cat_id"
          bordered
          columns={columns}
          dataSource={data}
          pagination={false}
          loading={loading}
        />

        <Pagination
          total={total}
          current={queryInfo.pagenum}
          pageSize={queryInfo.pagesize}
          showSizeChanger
          showTotal={showTotal}
          onChange={handlePagination}
        />
      </Card>
      <AddOrEditCategories 
        visible={isAddOrEdit}
        catInfo={catInfo}
        parentCate={parentCate}
        onHide={hideAddOrEdit}
      />
    </>
  )
}

export default CategoriesList